package nl.unimaas.micc.umsnooker.gameflow.phases;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;

import nl.unimaas.micc.umsnooker.domain.BilliardBall;
import nl.unimaas.micc.umsnooker.gameflow.GamePhase;
import nl.unimaas.micc.umsnooker.gameflow.GameState;
import nl.unimaas.micc.umsnooker.logic.GameLogicHandler;
import nl.unimaas.micc.umsnooker.simulation.InTimeSimulation;
import nl.unimaas.micc.umsnooker.simulation.PrescheduledSimulation;
import nl.unimaas.micc.umsnooker.simulation.Simulation;
import nl.unimaas.micc.umsnooker.simulation.event.CueInteraction;
import nl.unimaas.micc.umsnooker.simulation.event.Event;

public class SimulationPhase extends GamePhase
{
	private static final Logger logger = Logger.getLogger(SimulationPhase.class.getName());

	private Simulation sim;
	private GameLogicHandler logicHandler;
	private CueInteraction cueShot;

	public SimulationPhase(GameState s, CueInteraction cueShot)
	{
		super(s);
		setNext(new AimingPhase(state));
		this.cueShot = cueShot;

		this.sim = new PrescheduledSimulation(new HashSet<BilliardBall>(state.getBalls()), state.getTable());

		logicHandler = new GameLogicHandler(state);
		
		sim.addEventHandler(logicHandler);

	}

	@Override
	public void start()
	{
		super.start();
		final Set<Event> initEvents = new HashSet<Event>();
		initEvents.add(cueShot);
		Runnable simRunner = new Runnable()
		{

			@Override
			public void run()
			{
				sim.init(initEvents);				
			}
		};
		
		
		Thread preScheduleSim = new Thread(simRunner);
		preScheduleSim.start();
	}

	@Override
	public void finish()
	{
		if (isFinished())
		{
			return;
		}

		for (BilliardBall b : state.getBalls())
		{
			b.setTime(0);
		}
	
		logicHandler.updateState();
		

		if (logicHandler.cueBallPocketed())
		{				
			setNext(new BreakInitPhase(state));
		}
		else
		{
			setNext(new AimingPhase(state));
		}
		
		super.finish();
	
	}

	public Simulation getSimulation()
	{
		return sim;
	}
}